package com.shamine.kuaiqiao.blink.welcome

import android.Manifest
import android.app.Dialog
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import cn.bmob.v3.BmobUser
import dmax.dialog.SpotsDialog
import kotlinx.android.synthetic.main.activity_welcome.*
import com.shamine.kuaiqiao.blink.R
import com.shamine.kuaiqiao.blink.basic.BaseActivity
import com.shamine.kuaiqiao.blink.data.Passer
import com.shamine.kuaiqiao.blink.events.EventSignOut
import com.shamine.kuaiqiao.blink.gallery.GalleryActivity
import com.shamine.kuaiqiao.blink.tool.TextTool
import org.greenrobot.eventbus.Subscribe
import rx.Subscriber

/**
 * 欢迎界面,包含登陆和注册
 */
class WelcomeActivity : BaseActivity(),View.OnClickListener {
    @Subscribe
    override fun onSignOut(event: EventSignOut) {
        finish()
    }

    //过度动画
    private lateinit var animation: AlphaAnimation
    //是否已经登陆
    private var signedIn = false
    /**
     * flag of login or register mode
     * true is register
     */
    private var mode = false
    //用于登陆或注册的用户名
    private lateinit var mUsername: String
    //用于登陆或注册的密码
    private lateinit var mPasswords: String
    //等待提示
    private lateinit var dialog: Dialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_welcome)
        dialog = SpotsDialog(this,R.style.DialogWait)
        animation = AlphaAnimation(0.0F,1.0F)
        animation.duration = 2000
        animation.setAnimationListener(object: Animation.AnimationListener{
            override fun onAnimationStart(p0: Animation?) {
                //检查是否已经登陆
                if (BmobUser.getCurrentUser()!=null) signedIn = true
            }

            override fun onAnimationRepeat(p0: Animation?) {
            }

            override fun onAnimationEnd(p0: Animation?) {
                getPermission()
            }
        })
        textView.animation = animation
    }

    override fun onClick(p0: View?) {
        when(p0?.id){
            //登陆 注册
            R.id.login -> checkInput()
            R.id.register -> {convertLoginFormsToRegister()}

        }
    }

    /**
     * 检查获取权限
     */
    private fun getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                //do not have permissions ,ask for 'em
                ActivityCompat.requestPermissions(this
                        , arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                        ,1228)
            }else {
                //have permissions
                if (signedIn) goTo(GalleryActivity::class.java,true) else showLoginForms()
            }
        } else {
//            version lower than M
            if (signedIn) goTo(GalleryActivity::class.java,true) else showLoginForms()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when(requestCode){
            1228 -> {
                if (grantResults.isNotEmpty()
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    // 获得权限
                    if (signedIn) goTo(GalleryActivity::class.java,true) else showLoginForms()
                }else {
                    toast(this,getString(R.string.toast_permission_denied))
                    finish()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    //执行登陆或者注册前检查用户输入
    private fun checkInput() {
        mUsername = username.text.toString()
        mPasswords = passwords.text.toString()
        if (mUsername.isEmpty() || mPasswords.isEmpty()){
            toast(this,getString(R.string.toast_incomplete_info))
            return
        }
        dialog.show()
        when(mode){
            //注册
            true -> register(mUsername,mPasswords)
            //登陆
            false -> login(mUsername,mPasswords)
        }
    }

    //perform register
    private fun register(username: String, passwords: String){
        val user = BmobUser()
        user.username = username
        user.setPassword(TextTool().encryptPwd(passwords))
        user.signUpObservable(Passer::class.java).subscribe(object: Subscriber<Passer>(){
            override fun onError(throwable: Throwable?) {
                dialog.dismiss()
                if (throwable?.message.toString().contains("already taken"))
                    toast(this@WelcomeActivity,resources.getString(R.string.toast_username_exits))
                else
                    toast(this@WelcomeActivity,
                            resources.getString(R.string.toast_fail)+throwable?.message.toString())

                if (isUnsubscribed) unsubscribe()
            }

            override fun onCompleted() {
                if (isUnsubscribed) unsubscribe()
            }

            override fun onNext(passer: Passer?) {
                dialog.dismiss()
                goTo(GalleryActivity::class.java,true)
            }
        })
    }

    //perform login
    private fun login(username: String, passwords: String){
        val existingUser = arrayOf(
                "15692185814",
                "15692185813",
                "15840231863",
                "18620510716",
                "13643215943",
                "13084409464",
                "15327427020",
                "17852033321",
                "18991365916",
                "18762698110",
                "13635878243",
                "13864818336",
                "17854262006",
                "17637249418",
                "17326591619",
                "13793760322",
                "13904714104",
                "13606428658",
                "13999833831",
                "18839222365",
                "15668278331",
                "18670393049",
                "15692185815",
                "fghhhhh@qq.com",
                "15692185814",
                "15623155696",
                "493862839@qq.com",
                "15692185811",
                "SZX",
                "15692185812",
                "15692155913",
                "17768615079",
                "13403938144",
                "13824957100",
                "17667175342",
                "15655101053",
                "15589530850",
                "13880756386",
                "17393127533",
                "15836630806",
                "13065126912",
                "18669615006",
                "13658160856",
                "17765107318",
                "15165155723",
                "15889985055",
                "18296884762",
                "15832280773",
                "13845071443",
                "17637322272",
                "15836810526",
                "15826799383",
                "17557260288",
                "15522733889",
                "15364810093",
                "18631071889",
                "15897411076",
                "13151771520",
                "17304316390",
                "13330125141",
                "17605061100",
                "17361621053",
                "13968729555",
                "18927509947",
                "18655290795",
                "15898090072",
                "15832215701",
                "13246804059",
                "15307122296",
                "13104664121",
                "13168719262",
                "15770765761",
                "15109114970",
                "15101547300",
                "15127289053",
                "15980849970",
                "15284730911",
                "17707134773",
                "17647339098",
                "15620633715",
                "13870133686",
                "18629311183",
                "13705150947",
                "17671666654",
                "17693240050")
        val user = BmobUser()
        user.username = username
        if (username in existingUser)
            user.setPassword(passwords)
        else
            user.setPassword(TextTool().encryptPwd(passwords))
            user.loginObservable(Passer::class.java).subscribe(object: Subscriber<Passer>(){
            override fun onCompleted() {
            }

            override fun onNext(p0: Passer?) {
                dialog.dismiss()
                toast(this@WelcomeActivity,getString(R.string.toast_success))
                goTo(GalleryActivity::class.java,true)
            }

            override fun onError(p0: Throwable?) {
                dialog.dismiss()
                if (p0?.message.toString().contains("username or password incorrect"))
                    toast(this@WelcomeActivity,resources.getString(R.string.incorrect_password_or_username))
                else
                    toast(this@WelcomeActivity,p0?.message.toString())
            }
        })
    }

    private fun showLoginForms() {
        username.visibility = View.VISIBLE
        passwords.visibility = View.VISIBLE
        login.visibility = View.VISIBLE
        register.visibility = View.VISIBLE

    }

    /**
     * 去注册界面
     */
    private fun convertLoginFormsToRegister(){
        //enter register mode
        mode = true
        login.setTextColor(ContextCompat.getColor(this,R.color.white))
        login.text = getString(R.string.go_sign_up)
        login.background = getDrawable(R.color.colorPrimary)

        register.visibility = View.GONE
    }

    //BACK TO SIGN IN MODE
    private fun returnToSignIn(){
        mode = false
        login.setTextColor(ContextCompat.getColor(this,R.color.black))
        login.text = getString(R.string.button_login)
        login.background = getDrawable(R.color.white)

        register.visibility = View.VISIBLE
    }

    override fun onBackPressed() {
        if (mode){
            returnToSignIn()
        }else super.onBackPressed()
    }
}
